package is.ru.honn.rumblr.factory;

import is.ru.honn.rumblr.data.PostDetail;
import is.ru.honn.rumblr.domain.AbstractRumblrPost;
import is.ru.honn.rumblr.domain.QuotePost;
import is.ru.honn.rumblr.domain.RumblrPost;
import is.ru.honn.rumblr.util.XmlUtil;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class QuotePostFactory extends PostFactory
{
  @Override
  public RumblrPost createPostFromXML(Element e)
  {
    QuotePost post = new QuotePost();
    createHeader(post, e);
    post.setQuoteText(XmlUtil.getXPathValue(e, "quote-text"));
	post.setQuoteSource(XmlUtil.getXPathValue(e, "quote-source"));

    return post;
  }

    //Creates a list of postDetails for a Quote post(text, source and tags) and returns it.
  @Override
  public List<PostDetail> createPostDetails(AbstractRumblrPost post)
  {
      QuotePost quote = (QuotePost)post;
      List<String> tags = quote.getTags(); //gets the tags if there are any
      List<PostDetail> postDetails = new ArrayList<PostDetail>();
      PostDetail postDetail;

      postDetail = new PostDetail(quote.getId(), "quote-text", quote.getQuoteText());
      postDetails.add(postDetail);
      postDetail = new PostDetail(quote.getId(), "quote-source", quote.getQuoteSource());
      postDetails.add(postDetail);
      //Creates a new PostDetail for each tag.
      for (String tag: tags)
      {
          postDetail = new PostDetail(quote.getId(), "tag", tag);
          postDetails.add(postDetail);
      }

      return postDetails;
  }
  //Creates a Quote post sets it type and returns it, createPostFromType from postfactory calls this function
  @Override
  public AbstractRumblrPost createPostType(String type)
  {
      QuotePost quote = new QuotePost();
      quote.setType(type);  // Sets the type post
      return quote;
  }
   //Merges the list of details into the post, use a basic for loop for all the items in the list and
   // places them in the right field.
   @Override
   public  AbstractRumblrPost mergeDetailsWithPost(AbstractRumblrPost post, Collection<PostDetail> details)
   {
      QuotePost quote = (QuotePost)post;
      List<String> tags = new ArrayList<String>();
      for(PostDetail dt : details) // loops through all the details and places them in the right field or taglist
      {
          if(dt.getName().equals("quote-text"))
          {
              quote.setQuoteText(dt.getValue());
          }
          else if(dt.getName().equals("quote-source"))
          {
              quote.setQuoteSource(dt.getValue());
          }
          else if (dt.getName().equals("tag"))
          {
              tags.add(dt.getValue());
          }
      }
      quote.addTags(tags);  //Adds the tags into the post

      return quote;
   }
}
